import socket
import logging
import selectors
import time

FORMAT = "%(asctime)s %(threadName)s %(thread)d %(message)s"
logging.basicConfig(format=FORMAT,level=logging.INFO)

class HttpServer_IO:
    def __init__(self):
        self.server = socket.socket()
        self.server.bind(('127.0.0.1',80))
        self.server.listen()
        self.server.setblocking(False)

        self.selector = selectors.DefaultSelector()

    def start(self):
        key = self.selector.register(self.server, selectors.EVENT_READ, self.fn)
        logging.info(key)
        while True:
            events = self.selector.select()
            # print(len(events),'+++++++')
            for key, mask in events:
                logging.info(key)
                key.data(key.fileobj, mask)


    def fn(self,sock:socket.socket,mask):
        print('accept fn ~~~~~~~~~')
        newsock,raddr = sock.accept()
        newsock.setblocking(False)
        self.selector.register(newsock,selectors.EVENT_READ,self.response)

    def response(self,clientsock:socket.socket,mask):
        print('response function ~~~~~~~~~')
        with open("frank.html",'r') as f:
            ff = f.read()
            try:
                clientsock.send(ff.encode())
                self.selector.unregister(clientsock)
                time.sleep(0.01)
                clientsock.close()

            except Exception as e:
                logging.error(e)
                self.selector.unregister(clientsock)
                clientsock.close()

hs = HttpServer_IO()
hs.start()

